package com.whzykj.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.whzykj.common.DateUtil;
import com.whzykj.model.Customer;
import com.whzykj.model.Dictionary;
import com.whzykj.model.Userinfo;

public class UserController extends Controller {
	// 生成验证码
	public void imgCode() {
		renderCaptcha();
	}

	// 登录操作
	public void login() {
		String code = this.getPara("imgcode");
		String mCode = HashKit.md5(code.toUpperCase());
		// boolean result=validateCaptcha(code);
		String sCode = this.getCookie("_jfinal_captcha");
		// System.out.println(HashKit.md5("888888"));
		boolean result = mCode.equals(sCode);
		if (!result) {
			// this.renderJsp("/login/login.jsp");
			this.setAttr("LoginMsg", "您输入的验证码不正确");
			this.renderJsp("/login.jsp");
		} else {
			try {
				Userinfo userinfo = getModel(Userinfo.class);
				String username=userinfo.getStr("USERNAME");
				String password=userinfo.getStr("password");
				if(username==null || username.trim().length()==0){
					this.setAttr("LoginMsg", "用户名不能为空！");
					this.renderJsp("/login.jsp");
					return;
				}
				if(password==null || password.trim().length()==0){
					this.setAttr("LoginMsg", "密码不能为空！");
					this.renderJsp("/login.jsp");
					return;
				}else{
					password=HashKit.md5(password);
				}
				Object[] params = { username,password,username,password };
				Userinfo user = Userinfo.dao
						.findFirst(
								"select * from Userinfo where (username=? and password=? or mobile=? and password=?) and enable=1 and (role<=2 or role=8 or role=9)",
								params);
				if (user == null) {
					this.setAttr("LoginMsg", "您输入的用户名和密码不正确");
					this.renderJsp("/login.jsp");
				} else {
					this.setSessionAttr("LOGIN_USER", user);
					HttpSession session = this.getSession();
					// 设置会话过期时间为60分钟
					session.setMaxInactiveInterval(60 * 60);
//					this.renderJsp("/admin/index.jsp");
					this.redirect("/admin/index.jsp");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 进入到用户列表显示页面
	public void listUserBefore() {
		this.renderJsp("/admin/auth/userList.jsp");
	}

	// 查询用户列表
	public void listUserPage() {
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");
		String role=this.getPara("role");
		String username=this.getPara("username");
		String mobile=this.getPara("mobile");
		StringBuffer condition=new StringBuffer("");
		if(role!=null && !role.trim().equals("-1")){
			condition.append(" and ROLE="+role);
		}
		if(username!=null && username.trim().length()>0){
			condition.append(" and USERNAME like'%"+username+"%'");
		}
		if(mobile!=null && mobile.trim().length()>0){
			condition.append(" and MOBILE like'%"+mobile+"%'");
		}
		String sqlBefore = "select ui.*,dic.DICT_NAME  ";
		StringBuffer sqlAfter = new StringBuffer(
				" FROM userinfo ui inner join dictionary dic ");
		sqlAfter.append(" on ui.ROLE=CAST(dic.DICT_CODE AS signed) ");
		sqlAfter.append(" where dic.DICT_TYPE='USER_ROLE' and USERNAME<>'admin' ");
		sqlAfter.append(condition.toString());
		sqlAfter.append(" ORDER BY CREATE_TIME");
		Page<Userinfo> paginate = Userinfo.dao.paginate(page, rows, sqlBefore,
				sqlAfter.toString());
		Map map = new HashMap();
		map.put("rows", paginate.getList());
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}

	// 重置密码的功能
	public void resetPass() {
		Integer userid = this.getParaToInt("userid");
		String pass = this.getPara("password");
		Userinfo userinfo = null;
		userinfo = Userinfo.dao.findById(userid);
		userinfo.set("PASSWORD", HashKit.md5(pass));
		userinfo.set("INIT_PASS", pass);
		boolean update = false;
		try {
			update = userinfo.update();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.renderText(update ? "1" : "0");
	}

	// 更改用户登录状态
	public void changeEnable() {
		Integer userid = this.getParaToInt("userid");
		Integer status = this.getParaToInt("status");
		Userinfo userinfo = null;
		userinfo = Userinfo.dao.findById(userid);
		userinfo.set("ENABLE", status);
		boolean update = false;
		try {
			update = userinfo.update();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.renderText(update ? "1" : "0");
	}

	// 更新用户是否删除的状态
	public void changeStatus() {
		Integer userid = this.getParaToInt("userid");
		Integer status = this.getParaToInt("status");
		Userinfo userinfo = null;
		userinfo = Userinfo.dao.findById(userid);
		userinfo.set("IS_CANCEL", status);
		if (status == 1) {
			userinfo.set("ENABLE", 0);
		}
		boolean update = false;
		try {
			update = userinfo.update();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.renderText(update ? "1" : "0");

	}

	// 修改密码的功能
	public void editPass() {
		Object obj = this.getSessionAttr("LOGIN_USER");
		if (obj == null) { // 如果会话过期，则转到登录页面
			redirect("/login.jsp");
		}
		Userinfo userinfo = (Userinfo) obj;
		String newPass = this.getPara("newPass");
		String result = "0";
		if (newPass != null && newPass.length() >= 6) {
			String mCode = HashKit.md5(newPass.toUpperCase()); // 将密码转换为大写字母，并使用MD5加密
			userinfo.set("password", mCode);
			boolean res = userinfo.update();
			result = res ? "1" : "0";
		}
		this.renderText(result);
	}
	
	// 根据用户角色查询用户列表信息
	public void listUserByRole(){
		Integer roleId=this.getParaToInt(0);
		List<Userinfo> list=Userinfo.dao.find("SELECT * FROM userinfo where role="+roleId);
		Userinfo userinfo=new Userinfo();
		userinfo.set("userid", -1).set("username", "--- 请选择 ---");
		list.add(0, userinfo);
		this.renderJson(list);
	}

	// 退出登录
	public void exit() {
		this.getSession().invalidate();
		redirect("/login.jsp");
	}

	/**
	 * 查询用户角色列表
	 */
	public void findRoles(){
		String sql="SELECT dic.DICT_CODE,dic.DICT_NAME from dictionary dic where dic.DICT_TYPE='USER_ROLE'";
		List<Dictionary> dictList=Dictionary.me.find(sql);
		Dictionary dict=new Dictionary();
		dict.set("DICT_CODE", "-1").set("DICT_NAME", "请选择用户角色");
		dictList.add(0, dict);
		this.renderJson(dictList);
	}
	
	/**
	 * 进入到添加用户的页面
	 */
	public void addBefore(){
		this.renderJsp("/admin/auth/userAdd.jsp");
	}
	
	/**
	 * 添加用户信息
	 */
	public void addUser(){
		Userinfo userinfo=this.getModel(Userinfo.class);
		boolean res=Userinfo.dao.findExistsUser(userinfo.getStr("MOBILE"));
		if(res){
			this.setAttr("addMsg", "对不起，您输入的用户电话号码已经存在，用户添加失败！");
			this.renderJsp("/admin/auth/userAdd.jsp");
			return;
		}
		userinfo.set("CREATE_TIME", DateUtil.getNow());
		userinfo.set("IS_CANCEL", 0);
		userinfo.set("PASSWORD", HashKit.md5(userinfo.getStr("INIT_PASS").toUpperCase()));
		boolean add=userinfo.save();
		this.setAttr("addMsg", add?"用户信息添加成功":"用户信息添加失败");
		this.renderJsp("/admin/auth/userAdd.jsp");
	}
	
	/**
	 * 进入到修改用户信息的页面
	 */
	public void editBefore(){
		Integer userid=this.getParaToInt(0);
		Userinfo userinfo=Userinfo.dao.findById(userid);
		this.setAttr("userinfo", userinfo);
		this.renderJsp("/admin/auth/userEdit.jsp");
	}
	
	/**
	 * 保存修改后的用户信息
	 */
	public void editUser(){
		Userinfo userinfo=this.getModel(Userinfo.class);
		boolean update=userinfo.update();
		if(update){
			Userinfo user=Userinfo.dao.findById(userinfo.getInt("userid"));
			Customer customer=Customer.dao.findById(user.getInt("cust_id"));
			if(customer!=null){
				customer.set("cust_name", userinfo.getStr("username"));
				customer.set("mobile", userinfo.getStr("mobile"));
				customer.update();
			}
		}
		this.renderJsp("/admin/auth/userList.jsp");
		
	}
	
	/**
	 * 根据电话号码来寻找用户是否存在
	 */
	public void findExistsUser(){
		String mobile=this.getPara("mobile");
		boolean res=Userinfo.dao.findExistsUser(mobile);
		this.renderText(res?"1":"0");
	}
}
